<template>
    <div class="workarea">
        <div class="top-tool">
            <div class="item">
                <el-dropdown>
                    <span class="el-dropdown-link">
                        项目
                    </span>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item @click="doCreate">新建项目</el-dropdown-item>
                            <el-dropdown-item @click="openDlg">打开项目</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </div>
            <div class="item">
                <div>信息</div>
            </div>
            <div class="item">
                <div>新建</div>
            </div>
            <div class="item">
                <div>删除</div>
            </div>
            <div class="item">
                <div>详情</div>
            </div>
        </div>
        <div class="drawer" :style="catLeftStyle">
            <div class="icon-fe flex flex-align-c flex-center" @click="toggleShow">
                <el-icon size="25px" v-if="showMenu" color="#697B9D">
                    <Fold />
                </el-icon>
                <el-icon size="25px" v-else color="#697B9D">
                    <Expand />
                </el-icon>
            </div>
            <el-form :model="baseForm" label-position="left" label-width="100px">
                <el-form-item label="项目名称" prop="name">
                    <el-input v-model="baseForm.projectName" placeholder="请输入项目名称" />
                </el-form-item>
                <el-form-item label="项目代码" prop="name">
                    <el-input v-model="baseForm.projectCode" placeholder="请输入项目编码" />
                </el-form-item>
                <el-form-item label="项目地点" prop="name1">
                    <el-input v-model="baseForm.projectAddr" placeholder="请输入项目地点" />
                </el-form-item>
                <el-form-item label="合同日期" prop="dateRange">
                    <el-date-picker style="width:100%" clearable v-model="baseForm.contractDate" type="datetime"
                        value-format="YYYY-MM-DD" placeholder="请选择合同日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="期限" prop="dateRange">
                    <el-date-picker style="width:100%" clearable v-model="baseForm.contractDateEnd" type="datetime"
                        value-format="YYYY-MM-DD" placeholder="请选择期限">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="设计单位" prop="name2">
                    <el-input v-model="baseForm.designUnit" placeholder="请输入设计单位" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="saveProj">保存</el-button>
                </el-form-item>
                <el-form-item label="图纸列表" prop="name2">
                    <el-upload class="upload-demo" accept=".dwg" ref="uploadRef" action="" :auto-upload="false"
                        @change="oninput" :show-file-list="false">
                        <el-button type="primary">选取文件</el-button>
                    </el-upload>
                </el-form-item>
                <el-table :data="cadData" v-if="cadData.length" size="small" stripe border empty-text=""
                    style="margin-bottom: 15px">
                    <el-table-column type="index" align="center" label="序号"></el-table-column>
                    <el-table-column prop="cadFileName" align="center" label="名称"></el-table-column>
                    <el-table-column align="center" width="100px" label="操作">
                        <template #default="{ row, $index }">
                            <el-button type="primary" size="small" @click="handleLock(row)" link>查看</el-button>
                            <el-button type="primary" size="small" @click="deleteCAD(row)" link>删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
        </div>
        <!-- <div class="meshs" v-if="showEditor"> 
            <div v-for="( item, index) in meshMode" :key="index">
                <div class="bold">{{ item.name }}：</div>
                <div class="flex flex-wrap gap-10">
                    <div :class="['mesh',`mesh_${index}`]" v-for="(mesh, iindex) in item.sizes" :key="iindex" draggable="true">
                        {{ `${mesh.w}x${mesh.h}` }}
                    </div>
                </div>
            </div>
        </div> -->
        <div class="page" id="containtner" v-if="showEditor">
        </div>

        <el-dialog v-model="dialogTableVisible" title="项目列表" width="1200" @opened="onDlgopen">
            <div style="overflow: auto; height: 30rem;">
                <el-table :data="projectData" v-loading="tabloading" stripe>
                    <el-table-column property="projectName" label="项目名称" width="150" />
                    <el-table-column property="createDate" label="创建时间" width="200" />
                    <el-table-column property="modifyDate" label="最后修改时间" />
                    <el-table-column label="操作" align="center">
                        <template #default="scope">
                            <el-button link type="primary" @click="openProject(scope.row)">打开</el-button>
                            <!-- <el-button link type="primary" @click="openProjCAD(scope.row)">图纸</el-button> -->
                            <el-button link type="primary" @click="deleteProj(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-dialog>

        <el-dialog v-model="dialogCADVisible" title="图纸列表" width="800">
            <div style="overflow: auto; height: 30rem;">
                <el-table :data="cadData" v-loading="cadloading" stripe>
                    <el-table-column property="cadFileName" label="图纸名称" />
                    <el-table-column label="操作" align="center" width="150">
                        <template #default="scope">
                            <el-button link type="primary" @click="openCadFile(scope.row)">打开</el-button>
                            <el-button link type="primary">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

        </el-dialog>
    </div>
</template>
<script setup>
const baseUrl = location.origin + '/dev-api'

import { onMounted, ref } from 'vue';
import threeUtil from '@/utils/three/threeutil'
import { ElMessage, ElMessageBox } from 'element-plus';

import calculator, { geoTypes } from '@/utils/three/calculator'
import { usePermissionStore } from "@/stores/modules/permission";
import { meshMode } from '@/utils/three/attributes'

import { uploadCad, saveCadFile, queryProjects, queryProjCADInfo, queryCADFileInfo, saveProject, deleteProject, deleteCadFile } from "@/api/module2"

const uploadRef = ref()
const showEditor = ref(true)
const permissionStore = usePermissionStore()
const baseForm = ref({})
const tabDataList = ref([])
const showMenu = ref(false)
const catLeftStyle = ref({
    // 'width': "350px" 
    'left': "-350px"
})
let start = null;

const dialogTableVisible = ref(false)

const projectData = ref([])
const tabloading = ref(false)


const cadData = ref([])
const dialogCADVisible = ref(false)
const cadloading = ref(false)

const oninput = (e) => {
    // showEditor.value = false;
    // tabDataList.value.push(e)
    if (!baseForm.value.projectId) {
        ElMessage.warning('图纸必须挂载在项目下，请新建或打开项目！')
        return
    }
    doSUbmit(e.raw)
}
function toggleShow() {
    showMenu.value = !showMenu.value;
    if (showMenu.value) {
        catLeftStyle.value = {
            'left': "0"
        }
    } else {
        catLeftStyle.value = {
            'left': "-350px"
        }
    }
}

function handleLock(row) {
    // showEditor.value = false;
    openCadFile(row)
}
const doSUbmit = (file) => {
    let formData = new FormData()
    formData.append('cad', file)
    formData.append('projectId', baseForm.value.projectId)
    uploadCad(formData).then(res => {
        if (res.code == 0) {
            // showEditor.value = true
            nextTick(() => {
                // start = Date.now()
                // threeUtil.initScene('containtner')
                // threeUtil.render()
                // threeUtil.regDrop()
                // threeUtil.regClick()
                // threeUtil.regDrag()
                let data = res.data
                let cadEntitys = data.cadEntitys
                handleData(cadEntitys)
                openProjCAD(data, false)
            })
        } else {
            ElMessage.error('CAD文件解析失败！')
        }
    })
}

const handleData = (dataArr) => {
    let newData = dataArr.filter(e => geoTypes.includes(e.entityName)) //&& e.cadPoints.length == 4

    newData.forEach((element, index) => {
        if (element.points) {
            element.vectors = calculator.pointsFrom4To8(element.entityName, element.points, element.floorHeight || 38000, element.h || 500)
            // console.log(element,index)
            threeUtil.drawCube(element.vectors, element.entityName, element)
        }

    });
    threeUtil.regHover()

    let allVer = newData.map(e => e.vectors.slice(0, 4))
    let xArr = [], yArr = []
    allVer.forEach(elm => {
        let xpoints = elm.map(e => e[0])
        let ypoints = elm.map(e => e[1])
        xArr = xArr.concat(...xpoints)
        yArr = yArr.concat(...ypoints)
    })

    let minX = Math.min(...xArr)
        , minY = Math.min(...yArr)
        , maxX = Math.max(...xArr)
        , maxY = Math.max(...yArr)
    // console.log(Date.now() - start)
    threeUtil.setCamPosi(minX, minY, maxX, maxY)
}

function doCreate() {
    showMenu.value = false
    baseForm.value = {}
    cadData.value = []
    toggleShow()
}


function openDlg() {
    dialogTableVisible.value = true
}

function onDlgopen() {
    queryData()
}

const saveProj = () => {
    let params = { ...baseForm.value }
    saveProject(params).then(res => {
        console.log(res)
        if(res.code == 0){
            ElMessage.success(res.message || '保存成功!')
        }
    })
}

const queryData = (needInit) => {
    tabloading.value = true
    let params = {}
    queryProjects(params).then(res => {
        if (needInit) {
            if (res.code == 0 && res.data.length > 0) {
                let data = res.data[0]
                threeUtil.initScene('containtner')
                threeUtil.render()
                threeUtil.regDrop()
                threeUtil.regClick()
                threeUtil.regDrag()
                baseForm.value = data
                openProjCAD(data, needInit)
            } else {
                ElMessage.info("还没有项目，去新建一个吧！")
            }
        } else {
            projectData.value = res.data
            tabloading.value = false
        }
    })
}

const openProject = (data) => {
    baseForm.value = data
    dialogTableVisible.value = false
    showMenu.value = false
    toggleShow()
    openProjCAD(data, false)
}

const deleteProj = (data) => {
    ElMessageBox.confirm(
        '确定删除该项目吗?',
        '提示',
        {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            type: 'warning',
        }
    ).then(() => {
        let param = {
            projectId: data.projectId
        }
        deleteProject(param).then(res => {
            if(res.code == 0){
                ElMessage.success("删除成功")
                queryData()
            }else{
                ElMessage.error("删除失败")
            }
        })
    })
}

const deleteCAD = (data) => {
    ElMessageBox.confirm(
        '确定删除图纸吗?',
        '提示',
        {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            type: 'warning',
        }
    ).then(() => {
        let param = {
            cadFileId: data.cadFileId
        }
        deleteCadFile(param).then(res => {
            if(res.code == 0){
                ElMessage.success("删除成功")
                openProjCAD(data, false)
            }else{
                ElMessage.error("删除失败")
            }
        })
    })
}

const openProjCAD = (data, needInit) => {
    // !needInit && (dialogCADVisible.value = true)

    cadloading.value = true
    let param = {
        projectId: data.projectId
    }
    queryProjCADInfo(param).then(res => {
        cadloading.value = false
        cadData.value = res.data
        if (needInit) {
            openCadFile(cadData.value[0])
        }

    })
}

const openCadFile = (data) => {
    dialogCADVisible.value = false
    dialogTableVisible.value = false
    let param = {
        cadFileId: data.cadFileId,
        object_name: 'CadLwPolyline'
    }
    queryCADFileInfo(param).then(res => {
        handleData(res.data)
    })
}

onMounted(() => {
    queryData(true)
})


</script>
<style lang="scss" scoped>
.workarea {
    position: relative;
    height: 100%;

    .top-tool {
        height: 30px;
        background-color: #697B9D;
        border-bottom: 1px solid #ccc;
        display: flex;
        align-items: stretch;

        .item {
            color: #fff;
            font-size: 14px;
            cursor: pointer;
            align-content: center;

            >* {
                padding: 0 15px;
            }

            &:hover {
                background-color: #999;
            }

            .el-dropdown {
                color: inherit;
                display: block;
            }
        }
    }

    .drawer {
        // overflow: hidden;
        padding: 15px;
        padding-top: 30px;
        width: 350px;
        height: calc(100vh - 99px);
        position: absolute;
        background-color: #fff;
        box-shadow: 0px 16px 48px 16px rgba(0, 0, 0, .08), 0px 12px 32px rgba(0, 0, 0, .12), 0px 8px 16px -8px rgba(0, 0, 0, .16);

        :deep(.el-form-item__label) {
            font-weight: 700;
        }

        transition: all 0.5s ease-in-out;

        .icon-fe {
            padding: 3px;
            position: absolute;
            right: -30px;
            top: 0;
            cursor: pointer;
            background-color: #fff;
            border-radius: 0 5px 5px 0;
        }
    }

    .meshs {
        width: 200px;
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        background-color: #fff;

        .bold {
            font-weight: bold;
        }

        .gap-10 {
            gap: 10px;
        }

        .mesh {
            flex: 0 0 30%;
            aspect-ratio: 1/1;
            align-content: center;
            color: white;

            &_0 {
                background-color: darkviolet;
            }

            &_1 {
                background-color: #00BCD4;
            }

            &_2 {
                background-color: #FF9800;
            }
        }
    }

    .page {
        height: calc(100vh - 99px);
        // width: calc(100vw - 300px);
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #fff;
        border-radius: 5px;
    }
}
</style>